package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.UserHolder;
import com.itheima.reggie.domain.Cart;
import com.itheima.reggie.mapper.CartMapper;
import com.itheima.reggie.service.CartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
@Transactional
public class CartServiceImpl implements CartService {

    @Autowired
    private CartMapper cartMapper;

    //添加购物车
    @Override
    public Cart add(Cart cart) {

        //先查询数据库中有没有要添加的菜品或套餐
        LambdaQueryWrapper<Cart> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Cart::getUserId, UserHolder.get().getId())
                .eq(cart.getDishId()!=null, Cart::getDishId, cart.getDishId())
                .eq(cart.getSetmealId()!=null,Cart::getSetmealId, cart.getSetmealId());
        Cart cart1 = cartMapper.selectOne(wrapper);


        if (cart1 != null) { //存在
            cart1.setNumber(cart1.getNumber() + 1);//当前菜品加1
            cartMapper.updateById(cart1);
            return cart1;

        } else { //不存在新建保存
            cart.setNumber(1);
            cart.setUserId(UserHolder.get().getId());
            cart.setCreateTime(new Date());
            cartMapper.insert(cart);
            return cart;
        }
    }


    //查询用户购物车列表
    @Override
    public List<Cart> findList() {

        LambdaQueryWrapper<Cart> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Cart::getUserId, UserHolder.get().getId());
        return cartMapper.selectList(wrapper);
    }


    //修改购物车
    @Override
    public Cart update(Cart cart) {

        LambdaQueryWrapper<Cart> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Cart::getUserId, UserHolder.get().getId())
                .eq(cart.getDishId() != null, Cart::getDishId, cart.getDishId())
                .eq(cart.getSetmealId() != null, Cart::getSetmealId, cart.getSetmealId());
        Cart cart1 = cartMapper.selectOne(wrapper);


        cart1.setNumber(cart1.getNumber() - 1);
        if (cart1.getNumber() <= 0) {
            cartMapper.deleteById(cart1);
        } else {
            cartMapper.updateById(cart1);
        }
        return cart1;
    }


    //清空购物车
    @Override
    public void clean() {

        LambdaQueryWrapper<Cart> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Cart::getUserId,UserHolder.get().getId());
        cartMapper.delete(wrapper);

    }
}
